<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        :closable="false"
        show-icon
        center
      ></el-alert>
      <el-steps :active="parseInt(activeName)" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form :model="goodsList" ref="addFormRef" :rules="addFormRule" label-position="top">
        <el-tabs v-model="activeName" @tab-click="handleTabClick" tab-position="left" :before-leave="checkTabs">
        <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="goodsList.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
                <el-input v-model="goodsList.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
                <el-input v-model="goodsList.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
                <el-input v-model="goodsList.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
                <el-cascader
                    placeholder="请选择三级分类"
                    v-model="cateCheckedArrary"
                    :options="goodsCateList"
                    :props="cascaderProps"
                    @change="handleCascaderChange">
                </el-cascader>
            </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">
            <el-form-item :index="i" v-for="(item, i) in manyGoodsCateList" :key="item.id" :label="item.attr_name">
                <el-checkbox-group v-model="item.attr_vals">
                    <el-checkbox :label="itemChild" :index="i1" v-for="(itemChild, i1) in item.attr_vals" :key="itemChild.id"></el-checkbox>
                </el-checkbox-group>
            </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">
            <el-form-item :index="i" v-for="(item, i) in onlyGoodsCateList" :key="item.id" :label="item.attr_name">
                <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
            <el-upload
                class="upload-demo"
                :action="uploadPath"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :file-list="fileList"
                list-type="picture"
                :headers="resquestHeader">
  <el-button size="small" type="primary">点击上传</el-button>
  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
</el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4">
          <quill-editor v-model="goodsList.goods_introduce">
           </quill-editor>
           <el-row class="mt">
             <el-col>
               <el-button type="primary" @click="subGoodsList">提交商品</el-button>
             </el-col>
           </el-row>
        </el-tab-pane>
      </el-tabs>
      </el-form>
    </el-card>
    <el-dialog
  title="预览图片"
  :visible.sync="imgDialogVisible"
  width="50%"
  >
  <img :src="imgUrl" alt="" >
</el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  name: 'addGoods',
  data () {
    return {
      activeName: '0',
      goodsList: {
        goods_name: '',
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      addFormRule: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 12, message: '请输入2-12位的商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ]
      },
      cateCheckedArrary: [],
      goodsCateList: [],
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      manyGoodsCateList: [],
      onlyGoodsCateList: [],
      uploadPath: 'http://127.0.0.1:8888/api/private/v1/upload',
      fileList: [],
      resquestHeader: {
        Authorization: window.sessionStorage.getItem('token')
      },
      imgUrl: '',
      imgDialogVisible: false
    }
  },
  methods: {
    async getGoodsCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return
      this.goodsCateList = res.data
    //   console.log(this.goodsCateList)
    },
    async handleTabClick () {
      if (this.activeName === '1') {
        const { data: res } = await this.$http.get(`categories/${this.catId}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        if (res.meta.status !== 200) return
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.manyGoodsCateList = res.data
        console.log(this.manyGoodsCateList)
      } else if (this.activeName === '2') {
        const { data: res } = await this.$http.get(`categories/${this.catId}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        if (res.meta.status !== 200) return
        this.onlyGoodsCateList = res.data
        console.log(this.onlyGoodsCateList)
      }
    },
    handleCascaderChange () {
      if (this.cateCheckedArrary.length !== 3) {
        this.cateCheckedArrary = []
      }
      this.goodsList.goods_cat = this.cateCheckedArrary
    },
    checkTabs (activeName, oldActiveName) {
      if (this.activeName === '0' && this.cateCheckedArrary.length !== 3) {
        this.$message.error('请选择商品三级分类')
        return false
      }
    },
    handlePreview (file) {
      // console.log(file)
      this.imgDialogVisible = true
      this.imgUrl = file.response.data.url
      // console.log(this.imgUrl)
    },
    handleRemove (file) {
      const path = file.response.data.tmp_path
      const index = this.goodsList.pics.findIndex(item => {
        return item.pic === path
      })
      this.goodsList.pics.splice(index, 1)
      console.log(this.goodsList)
    },
    handleSuccess (response, file) {
      const picInfo = { pic: response.data.tmp_path }
      this.goodsList.pics.push(picInfo)
      // console.log(this.goodsList)
    },
    subGoodsList () {
      // console.log(this.goodsList)
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项')
        }
        const newForm = _.cloneDeep(this.goodsList)
        // console.log(newForm)
        newForm.goods_cat = newForm.goods_cat.join(',')
        this.manyGoodsCateList.forEach(item => {
          const manyParams = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.goodsList.attrs.push(manyParams)
        })
        this.onlyGoodsCateList.forEach(item => {
          const onlyAttr = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.goodsList.attrs.push(onlyAttr)
        })
        newForm.attrs = this.goodsList.attrs
        console.log(newForm)
        const { data: res } = await this.$http.post('goods', newForm)
        console.log(res)
        if (res.meta.status !== 201) return
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  },
  created () {
    this.getGoodsCateList()
  },
  computed: {
    catId () {
      if (this.cateCheckedArrary.length === 3) {
        return this.cateCheckedArrary[2]
      }
      return false
    }
  }
}
</script>
<style lang="less" scoped>
.mt{
  margin-top: 15px;
}
</style>
